package com.firewolf.struts.fileupload.service;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.firewolf.struts.fileupload.models.User;
import com.firewolf.struts.fileupload.utils.DBUtil;

public class UserService {

	/**
	 * @Description: 添加用户 @输入和输出示例： @思路：
	 * @param user
	 * @throws SQLException 
	 */
	public void addUser(User user) throws SQLException {

		String insertSql = "insert into users (name,orignphoto,newphoto) values (?,?,?)";
		Object[] paras = { user.getName(), user.getOrignPhoto(), user.getNewPhoto() };
		DBUtil.getInstance().doUpdate(insertSql, paras);
	}

	/**
	 * @Description: 获取所有用户 @输入和输出示例： @思路：
	 * @return
	 * @throws SQLException 
	 */
	public ArrayList<User> getAllUsers() throws SQLException {
		String sql = "select name,orignphoto,newphoto from users";
		List<Object[]> list = DBUtil.getInstance().doQuery(sql, null);
		ArrayList<User> users = new ArrayList<>();
		for(int i = 0 ;i<list.size();i++){
			Object[] pros = list.get(i);
			User user = new User();
			user.setName((String) pros[0]);
			user.setOrignPhoto((String)pros[1]);
			user.setNewPhoto((String)pros[2]);
			users.add(user);
		}
		return users;
	}

	/**
	 * @Description: 根据用户名查询用户
	 * @输入和输出示例：
	 * @思路：
	 * @param userName
	 * @return
	 * @throws SQLException 
	 */
	public User getUserByName(String userName) throws SQLException {
		String sql = "select name,orignphoto,newphoto from users where name=? ";
		ArrayList<Object[]> objs = DBUtil.getInstance().doQuery(sql, new String[]{userName});
		Object[] o = objs.get(0);
		User user = new User();
		user.setName((String) o[0]);
		user.setOrignPhoto((String) o[1]);
		user.setNewPhoto((String) o[2]);
		return user;
	}
}
